package com.sc.study.exam.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.*;

import com.sc.common.config.SCConfig;
import com.sc.common.utils.file.FileUploadUtils;
import com.sc.study.exam.domain.ScQuestionOption;
import com.sc.study.exam.mapper.ScQuestionOptionMapper;
import com.sc.study.exam.mapper.ScQuestionTypeMapper;
import com.sc.study.foundation.mapper.ScSubjectChapterMapper;
import com.sc.study.foundation.mapper.ScSubjectMapper;
import com.sc.study.foundation.service.IScSubjectChapterService;
import com.sc.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.sc.study.exam.mapper.ScQuestionMapper;
import com.sc.study.exam.domain.ScQuestion;
import com.sc.study.exam.service.IScQuestionService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import static java.util.stream.Collectors.toList;

/**
 * 题目Service业务层处理
 *
 * @author sc
 * @date 2022-02-27
 */
@Service
public class ScQuestionServiceImpl implements IScQuestionService {

    @Value("${sc.profile}")
    private String fileImagesUrl;

    @Autowired
    private ScQuestionMapper scQuestionMapper;

    @Autowired
    private ScQuestionOptionMapper scQuestionOptionMapper;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private ScSubjectMapper scSubjectMapper;

    @Autowired
    private ScQuestionTypeMapper scQuestionTypeMapper;

    @Autowired
    private IScSubjectChapterService subjectChapterService;

    /**
     * 查询题目
     * 若是选择题则带出选择题答案出去
     *
     * @param id 题目主键
     * @return 题目
     */
    @Override
    public ScQuestion selectScQuestionById(Long id) {
        ScQuestion scQuestion = scQuestionMapper.selectScQuestionById(id);

        //设置问题类型
        scQuestion.setScQuestionType(scQuestionTypeMapper.selectScQuestionTypeById(scQuestion.getQuestiontypeid()));

        //判断是否为选择题
        String question_type_option = sysConfigService.selectConfigByKey("question_type_option");
        if (scQuestion.getQuestiontypeid().toString().equals(question_type_option)) {
            //设置当前题目的所有题目选项
            scQuestion.setQuestionOptions(scQuestionOptionMapper.selectScQuestionOptionByQuestionId(scQuestion.getId()));

            //设置为是否选中状态
            scQuestion.getQuestionOptions().forEach(item -> {
                if (scQuestion.getAnswer().contains(item.getId().toString())) item.setCheck(true);
            });
        }
        return scQuestion;
    }

    /**
     * 查询题目列表
     * 设置科目对象 问题类型
     *
     * @param scQuestion 题目
     * @return 题目
     */
    @Override
    public List<ScQuestion> selectScQuestionList(ScQuestion scQuestion) {
        List<ScQuestion> scQuestions = scQuestionMapper.selectScQuestionList(scQuestion);

        //设置科目对象 问题类型
        scQuestions.forEach(item -> {
            item.setScQuestionType(scQuestionTypeMapper.selectScQuestionTypeById(item.getQuestiontypeid()));
            item.setScSubject(scSubjectMapper.selectScSubjectBySubid(item.getSubjectid()));
        });

        return scQuestions;
    }

    /**
     * 新增题目:
     * 再新增出子类： 题目选择
     *
     * @param scQuestion 题目
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertScQuestion(ScQuestion scQuestion, MultipartFile[] multipartFiles, String url) throws IOException {

        //获取参数键值 判断是否为问题操作类型答案
        String question_type_operate = sysConfigService.selectConfigByKey("question_type_operate");

        String operateAnswerPrefix = sysConfigService.selectConfigByKey("operate_answer_prefix");

        if (question_type_operate.equals(scQuestion.getQuestiontypeid().toString())) {
            StringBuilder answerStr = new StringBuilder(operateAnswerPrefix);
            for (MultipartFile multipartFile : multipartFiles) {

                String filePath = SCConfig.getUploadPath();

                String upload = FileUploadUtils.upload(filePath, multipartFile);
                answerStr.append(url + upload + ",");
            }
            scQuestion.setAnswer(answerStr.toString());
        }

        int i = scQuestionMapper.insertScQuestion(scQuestion);

        //获取参数键值 判断是否为问题选择类型答案
        String question_type_option = sysConfigService.selectConfigByKey("question_type_option");
        if (question_type_option.equals(scQuestion.getQuestiontypeid().toString())) {
            List<ScQuestionOption> questionOptions = scQuestion.getQuestionOptions();

            questionOptions.forEach(item -> {           //设置题目id值
                item.setQuestionid(scQuestion.getId());
            });

            //批量插入题目选项
            scQuestionOptionMapper.batchInsert(questionOptions);


            //获取 answer 列 的值
            List<Long> answerList = new ArrayList<>();
            questionOptions.forEach(item -> {
                if (item.getCheck()) answerList.add(item.getId());
            });

            scQuestion.setAnswer(answerList.toString()
                    .replace('[', ' ')
                    .replace(']', ' '));

            //修改题目中的 answer 列
            scQuestionMapper.updateScQuestion(scQuestion);
        }


        return i;
    }

    /**
     * 修改题目
     *
     * @param scQuestion
     * @param fileImages   添加的操作题目的文件 img
     * @param removeImages 操作题目需要删除的文件路径
     * @return 结果
     */
    @Override
    @Transactional
    public int updateScQuestion(ScQuestion scQuestion, MultipartFile[] fileImages, String[] removeImages, String url) throws IOException {
        //判断是否为操作题
        String question_type_operate = sysConfigService.selectConfigByKey("question_type_operate");
        if (question_type_operate.equals(scQuestion.getQuestiontypeid().toString())){
            for (String removeImage : removeImages) {
                new File(removeImage.replaceAll(url, fileImagesUrl + "/")).delete();
                scQuestion.setAnswer(scQuestion.getAnswer().replaceAll(removeImage.concat(","), ""));
            }
            StringBuilder answerStr = new StringBuilder();

            if (fileImages != null){
                for (MultipartFile multipartFile : fileImages) {
                    //获取前缀
                    String fileName = UUID.randomUUID().toString();
                    //获取后缀
                    String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
                    File file = new File(fileImagesUrl + "/" + fileName + suffix);
                    multipartFile.transferTo(file);
                    answerStr.append(url + fileName + suffix + ",");
                }

                scQuestion.setAnswer(scQuestion.getAnswer().concat(answerStr.toString()));
            }
        }


        //判断是否为选择题
        String question_type_option = sysConfigService.selectConfigByKey("question_type_option");
        if (question_type_option.equals(scQuestion.getQuestiontypeid().toString())) {


            //删除所有题目选项
            scQuestionOptionMapper.deleteScQuestionOptionByQuestionIds(scQuestion.getId());

            /**
             * 批量添加题目
             */
            List<ScQuestionOption> questionOptions = scQuestion.getQuestionOptions(); //批量插入的题目选项
            questionOptions.forEach(item -> {           //设置题目id值
                item.setQuestionid(scQuestion.getId());
            });

            if (questionOptions != null && questionOptions.size() > 0)
                scQuestionOptionMapper.batchInsert(questionOptions);

            /**
             * 获取被选中的题目选项集合
             */
            List<Long> answerList = new ArrayList<>();              //被选中的题目选项集合
            questionOptions.forEach(item -> {
                if (item.getCheck()) answerList.add(item.getId());       //添加被选中的题目选项值
            });

            //设置 answer 数据
            scQuestion.setAnswer(answerList.toString()
                    .replace('[', ' ')
                    .replace(']', ' '));
        }

        return scQuestionMapper.updateScQuestion(scQuestion);
    }

    /**
     * 批量删除题目
     *
     * @param ids 需要删除的题目主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteScQuestionByIds(Long[] ids) {
        int i = scQuestionMapper.deleteScQuestionByIds(ids);

        //批量删除题目选项
        scQuestionOptionMapper.deleteScQuestionOptionByQuestionIds(ids);

        return i;
    }

    /**
     * 删除题目信息
     *
     * @param id 题目主键
     * @return 结果
     */
    @Override
    public int deleteScQuestionById(Long id) {
        return scQuestionMapper.deleteScQuestionById(id);
    }

    /**
     * 批量添加题目信息
     *
     * @param scQuestionList
     * @return
     */
    @Override
    @Transactional
    public int batchScQuestion(List<ScQuestion> scQuestionList) {

        Map<Long, Long> scSubjectChapterMap = subjectChapterService.selectSubjectChapterMap();

        //设置科目id
        scQuestionList.forEach(item -> item.setSubjectid(scSubjectChapterMap.get(Long.valueOf(item.getChapterid().toString()))));

        //批量增加
        scQuestionMapper.batchScQuestion(scQuestionList);

        //获取选择 id值
        Long question_type_option = Long.valueOf(sysConfigService.selectConfigByKey("question_type_option"));


        scQuestionList.forEach(scQuestion -> {
            if (question_type_option == scQuestion.getQuestiontypeid()) {
                List<ScQuestionOption> questionOptions = scQuestion.getQuestionOptions();
                questionOptions.forEach(option -> {
                    option.setQuestionid(scQuestion.getId());
                });
                scQuestionOptionMapper.batchInsert(questionOptions);


                List<Long> answerList = new LinkedList<>();
                questionOptions.forEach(item -> {
                    if (item.getCheck()) answerList.add(item.getId());
                });
                String answer = answerList.toString().replace("[", "").replace("]", "").trim();
                scQuestion.setAnswer(answer);
                scQuestionMapper.updateScQuestion(scQuestion);
            }
        });

        return 1;
    }

    /**
     * 根据试卷id查询出题目
     * @param testId 试卷id
     * @return
     */
    @Override
    public List<ScQuestion> selectByTestId(Integer testId,ScQuestion scQuestion) {
        return scQuestionMapper.selectByTestId(testId,scQuestion);
    }

    /**
     * 根据试卷id查询未绑定的题目
     * @param scQuestion
     * @return
     */
    @Override
    public List<ScQuestion> selectByNotExistTestId(ScQuestion scQuestion) {
        return scQuestionMapper.selectByNotExistTestId(scQuestion);
    }

    /**
     * 获取某个试卷的所有题目， 并绑定学生的答题
     * @param studentId 学生id
     * @param testExamId 考试编号
     * @return
     */
    @Override
    public List<ScQuestion> listCanJoinStudentExamResult(Integer studentId, Integer testExamId) {
        return scQuestionMapper.listCanJoinStudentExamResult(studentId, testExamId);
    }
}
